import React, { PureComponent } from "react";
import { connect } from "dva";
import { Modal, Row, Col, Form, Input, Select, DatePicker, Icon, Button, AutoComplete, message} from "antd";
import Upload from "../../../components/Upload";



const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;



const beforeUpload = file => {
  // const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isFile  = file.type === "application/msword" || file.type ==="application/vnd.openxmlformats-officedocument.wordprocessingml.document" || file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || file.type === "application/pdf" ;
  if (!isFile) {
    message.error("仅允许上传Word、Excel、PDF文件!");
  }
  const isLt2M = file.size / 1024 / 1024 < 5;
  if (!isLt2M) {
    message.error("图片文件不能大于5MB!");
  }
  return isFile && isLt2M;
};



@connect(({ repository, global }) => ({
  // baseUrl:global.baseUrl,
  loading:repository.loading,
}))
@Form.create()
export default class EquipmentAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.state={
      fileList: null,
    }
  }

  componentDidMount() {
    // 获取所有下拉数据的datasource
    // this.props.dispatch({
    //   type: "equipment_integrated/fetch_selectsource_for_add",
    // })
  }



  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch,fileFolder } = this.props;
        dispatch({
            type: `repository/add_repository`,
            payload: {
              ...values,
              fileFolder,
            }
          })
          .then(() => {
            this.handleReset();
            this.handleCancel();
            this.props.callback();
          });
      }
    });
  }

  handleReset = () => {
    this.setState({
      fileUrl: null,
    })
    this.props.form.resetFields();
  };

  handleCancel = () => {
    this.handleReset();
    this.props.onCancel(false);
  };




  // 多文件上传
  uploadFile = e => {
    let file_url=null;
    if (e.file.status === "done" && e.file.response && e.file.response.data && e.file.response.data.token) {
      file_url = e.file.response.data.token;
    }
    return file_url;
  };



  handleUploadFiles = info => {
    const { detailId } = this.props;
    let fileList = info.fileList;
    // 1. Limit the number of uploaded files
    // Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-1);

    if (info.file.status == "done") {
      //const filename_str = info.file.name.split(".");
      // this.props.form.setFieldsValue({
      //   project_name: filename_str[0]
      // });

      fileList = fileList.map(item => {
        if (item.response && item.response.error_no != "0") {
          item.status = "error";
        }
        return item;
      });
    }

    this.setState({ fileList });
  };

  handleRemoveUploadFiles = file => {};




  render() {
    const { visible, loading } = this.props;
    const { fileList } = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 }
    };

    // console.log(selectSource);

    const uploadButton = (
      <div>
        <Icon type={this.state.loading_picupload ? "loading" : "plus"} />
        <div className="ant-upload-text">上传</div>
      </div>
    );


    return (
      <div>
        <Modal
          title={"添加文档"}
          okText={'提交'}
          visible={visible}
          onOk={this.handleSubmit.bind(this)}
          confirmLoading={loading.model_submit}
          onCancel={this.handleCancel}
          width={500}
        >
          <Form layout="horizontal">
            <Row gutter={24}>
              <Col span={24}>
                <FormItem {...formItemLayout} label="文档编号" colon={false}>
                  {getFieldDecorator("fileCode", {
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入文档编号" />
                  )}
                </FormItem>
              </Col>
              <Col span={24}>
                <FormItem {...formItemLayout} label="文档名称" colon={false}>
                  {getFieldDecorator("fileTitle", {
                    rules: [
                      { required: true, message: "请输入文档名称" },
                    ]
                  })(
                    <Input placeholder="请输入文档名称" />
                  )}
                </FormItem>
              </Col>
              <Col span={24}>
                <FormItem {...formItemLayout} label="关键字" colon={false}>
                  {getFieldDecorator("keyword", {
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入文档名称" />
                  )}
                </FormItem>
              </Col>

              <Col span={24}>
                <FormItem {...formItemLayout} label="备注" colon={false}>
                  {getFieldDecorator("remarks", {
                    rules: [{ max: 100, message: "不超过100个字" }]
                  })(
                    <TextArea
                      placeholder="请输入备注内容"
                      autosize={{ minRows: 3, maxRows: 6 }}
                    />
                  )}
                </FormItem>
              </Col>


              <Col span={24}>
                <FormItem
                  {...formItemLayout}
                  label="上传文档"
                  colon={false}
                >
                  {getFieldDecorator("filePath", {
                    valuePropName: "file",
                    getValueFromEvent: this.uploadFile,
                    rules: [
                        { required: true, message: "请上传文档" },
                    ]
                  })(
                    <Upload
                      // defaultFileList={detailId === 0 ? null : detaildata.devDatum}
                      fileList={this.state.fileList}
                      onChange={this.handleUploadFiles}
                      onRemove={this.handleRemoveUploadFiles}
                      beforeUpload={beforeUpload}
                    >
                      <Button>
                        <Icon type="upload" /> 上传
                      </Button>
                    </Upload>
                  )}
                </FormItem>
              </Col>



            </Row>
          </Form>

        </Modal>

      </div>
    );
  }
}
